#!/usr/bin/env python
# encoding: utf-8
from flask import Flask,request,url_for,g,render_template,session,redirect,flash
from flask.ext.sqlalchemy import SQLAlchemy
from models import contact,db,app,computer
import config
import sys

reload(sys)
sys.setdefaultencoding('utf-8')

app.config.from_object(config)
app.secret_key=app.config['SECERT_KEY']


@app.route("/admin/my")
def myadmin():
    if session.has_key('is_login') and session['username'] == app.config['USERNAME']:
        return render_template('my-profile.html')
    else:
        return redirect(url_for('admin'))






@app.route("/admin",methods=['POST','GET'])
def admin():
    if request.method == 'POST':
        if request.form['username'] != app.config['USERNAME'] or request.form['password'] != app.config['PASSWORD']:
            flash("用户名密码错误")
        else:
            session['is_login'] = True
            session['username'] = app.config['USERNAME']
            return redirect(url_for('myadmin'))
    return render_template('login.html')

@app.route('/')
@app.route("/index")
def index():
    return redirect(url_for('admin'))


@app.route("/admin/add",methods=["POST","GET"])
def add():
    if session.has_key('is_login') and session['username'] == app.config['USERNAME']:
        if request.method == "POST":
            con = contact(request.form['username'],request.form['job'],request.form['tel'],request.form['number'])
            print con
            print(request.form['username'],request.form['job'],request.form['tel'],request.form['number'])
            db.session.add(con)
            db.session.commit()
            flash("add success")
            return render_template("new-user.html")
        else:
            return render_template("new-user.html")
    else:
        return redirect(url_for("admin"))

@app.route("/admin/show")
@app.route("/admin/show<int:page>")
def show(page=1):
    if session.has_key('is_login') and session['username'] == app.config['USERNAME']:
        data = contact.query.order_by(contact.number.desc()).paginate(page,10,False)
        current = data.items
        return render_template("list_users.html",pagination=data,contactdata=current)
    else:
        return redirect(url_for("admin"))

@app.route("/admin/del/<int:page>")
def delete(page):
    if session.has_key('is_login') and session['username'] == app.config['USERNAME']:
        status = contact.query.filter(contact.id==page).first()
        if status == None:
            flash("delete failue")
            return redirect(url_for('show'))
        db.session.delete(status)
        db.session.commit()
        flash("delete success")
        return redirect(url_for('show'))
    else:
        return redirect(url_for('admin'))

@app.route("/admin/update/<int:page>",methods=["POST","GET"])
def update(page):
    if session.has_key('is_login') and session['username'] == app.config['USERNAME']:
        if request.method == "POST":
            con = contact.query.get(page)
            if con == None:
                flash("update error")
                return redirect(url_for('show'))
            con.username = request.form['username']
            con.job = request.form['job']
            con.tel = request.form['tel']
            con.number = request.form['number']
            db.session.commit()
            flash("update secess")
            return redirect(url_for('show'))
        contactdata = contact.query.get(page)
        if contactdata == None:
            return render_template("user-update.html")
        return render_template("user-update.html",data=contactdata)
    else:
        return redirect(url_for('admin'))



@app.route("/admin/addpc",methods=["POST","GET"])
def addpc():
    if session.has_key('is_login') and session['username'] == app.config['USERNAME']:
        if request.method == "POST":
            con = computer(request.form['number'],request.form['username'],request.form['job'],request.form['ip'],request.form['mac'],request.form['mark'])
            print con

            print(request.form['number'],request.form['username'],request.form['job'],request.form['ip'],request.form['mac'],request.form['mark'])
            db.session.add(con)
            db.session.commit()
            flash("add success")
            return render_template("addpc.html")
        else:
            return render_template("addpc.html")
    else:
        return redirect(url_for("admin"))



@app.route("/admin/lists_pc")
@app.route("/admin/lists<int:page>")
def lists_pc(page=1):
    if session.has_key('is_login') and session['username'] == app.config['USERNAME']:
        data = computer.query.order_by(computer.number.desc()).paginate(page,10,False)
        current = data.items
        return render_template("lists_pc.html",pagination=data,contactdata=current)
    else:
        return redirect(url_for("admin"))



@app.route("/admin/del_pc/<int:page>")
def del_pc(page):
    if session.has_key('is_login') and session['username'] == app.config['USERNAME']:
        status = computer.query.filter(computer.id==page).first()
        if status == None:
            flash("delete failue")
            return redirect(url_for('lists_pc'))
        db.session.delete(status)
        db.session.commit()
        flash("delete success")
        return redirect(url_for('lists_pc'))
    else:
        return redirect(url_for('admin'))

@app.route("/admin/update_pc/<int:page>",methods=["POST","GET"])
def update_pc(page):
    if session.has_key('is_login') and session['username'] == app.config['USERNAME']:
        if request.method == "POST":
            con = computer.query.get(page)
            if con == None:
                flash("update error")
                return redirect(url_for('lists_pc'))
            con.number = request.form['number']
            con.username = request.form['username']
            con.job = request.form['job']
            con.ip = request.form['ip']
            con.mac = request.form['mac']
            con.mark = request.form['mark']
            print con.mark
            db.session.commit()
            flash("update secess")
            return redirect(url_for('lists_pc'))
        contactdata = computer.query.get(page)
        if contactdata == None:
            return render_template("update_pc.html")
        return render_template("update_pc.html",data=contactdata)
    else:
        return redirect(url_for('admin'))



@app.route("/search/")
def search():
    if session.has_key('is_login') and session['username'] == app.config['USERNAME']:
        db.session.commit()
        pp = request.args.get('q','',type=str)
        current=contact.query.whoosh_search(pp).all()
        db.session.commit()
        return render_template("user-search.html",contactdata=current)
    else:
        return redirect(url_for('admin'))



@app.route("/ipsearch/")
def ipsearch():
    if session.has_key('is_login') and session['username'] == app.config['USERNAME']:
        db.session.commit()
        pp = request.args.get('q','',type=str)
        current=computer.query.whoosh_search(pp).all()
        db.session.commit()
        return render_template("ipsearch.html",contactdata=current)
    else:
        return redirect(url_for('admin'))



@app.route("/logout")
def logout():
    session.pop('is_login',None)
    session.pop('username',None)
    flash("YOU were log out")
    return redirect(url_for('admin'))





if __name__=="__main__":
    app.run(host="0.0.0.0",port=8000,debug=True)




